import { tokenReloadRequest } from "@/http/api/index.js";
import axios from "axios";
import Cookies from "js-cookie";
export const tokenGet = () => {
  return Cookies.get("authorization");
};
export const tokenSet = (token, time, type) => {
  let usetime = +new Date() + Number(time) * 24 * 3600 * 1000
  const expires = new Date(usetime);
  Cookies.set("authorization", token, {
    expires: expires,
    secure: true,
    sameSite: "strict",
  });
  localStorage.setItem(tokenReload.loginTitle, usetime);
  if (type) {
    localStorage.setItem(tokenReload.timeTitle, +new Date());
  }
  return;
};
export const tokenCheck = () => {
  let token = Cookies.get("authorization");
  if (token) {
    return +new Date() > Number(localStorage.getItem(tokenReload.loginTitle));
  } else {
    return false;
  }
};
export const deleteToken = () => {
  Cookies.remove("authorization");
  localStorage.removeItem(tokenReload.loginTitle);
  localStorage.removeItem(tokenReload.timeTitle);
  return;
};
export const loginReload = () => {
  console.log("回到首页的删除");
  deleteToken();
  window.location.href = window.location.origin + "/#/login";
};

export let tokenReload = {
  loading: false,
  timeout: 24 * 60 * 60 * 1000,
  timeTitle: "tokenReloadTime",
  loginTitle: "expiredTime",
  requestCache: [],

  load(type, config) {
    if (!this.loading) {
      this.loading = true;
    }
    const that = this;
    tokenReloadRequest().then((res) => {
      if (res.code != 200) {
        // 请求失败
        // loginReload();
        console.log("12")
        return;
      } else {
        tokenSet(res.token, 1, 1);
        that.requestCache.forEach((resolve) => {
          if (type == "request") {
            resolve();
          } else {
            resolve.resolve(axios.request(resolve.config));
          }
        });
        that.requestCache = [];
      }
    });
    return new Promise((resolve, reject) => {
      if (type == "request") {
        that.requestCache.push[resolve];
      } else {
        that.requestCache.push[{ config: config, resolve: resolve }];
      }
    });
  },
  reloadCheck() {
    return +new Date() - Number(localStorage.getItem(this.timeTitle) || 0) > this.timeout;
  },
};
